<template>

  <div class="joe_main">

    <!--    <ants-baberrage :danmus="data"/>-->
    <div class="joe_comment">

      <!-- 评论区 -->
      <h3 class="joe_comment__title">留言 ({{ leavingMessageSize }})</h3>

      <div id="respond-page-1176" class="joe_comment__respond">
        <div class="joe_comment__respond-form">
          <div class="body">
            <ants-leave-message @doSend="doSend" :commentList="data" @doChidSend="doChidSend"/>
            <a-spin tip="Loading..." v-if="data.length == 0">
              <div class="spin-content">
              </div>
            </a-spin>
          </div>

        </div>
      </div>
      <div>
        <a-pagination
          style="text-align: center"
          :default-current="1"
          :page-size.sync="pagination.pageSize"
          :total="pagination.total"
          @change="onChange"
          @showSizeChange="onShowSizeChange"
        />
      </div>
    </div>
    <a-modal
      :width="600"
      :visible="personInfoVisible"
      :confirm-loading="confirmLoading"
      cancel-text="关闭"
      @ok="doOk"
      @cancel="doCancel"
    >
      <a-form :form="form">
        <a-row>
          <a-col :span="24">
            <a-form-item label="昵称" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-input @blur="getQqInfo()" v-decorator="['nickname', validatorRules.nickname]"
                       placeholder="输入QQ号自动获取昵称、邮箱、头像..."
              />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="邮箱" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-input v-decorator="['email', validatorRules.email]" placeholder="请输入真实邮箱，用于接收回信..."/>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="网站地址" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-input v-decorator="['url']" placeholder="请输入网址（非必填）..."/>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="头像" :label-col="labelCol" :wrapper-col="wrapperCol">
              <ants-image-upload v-decorator="['avatar']" :disabled="true" text="头像"/>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>
  </div>
</template>


<script>
import {getAction, postAction} from '@/api/manage'
import {filterObj} from '@/utils/util'
import AntsBaberrage from '@/components/ants/AntsBaberrage'
import AntsLeaveMessage from '@/components/ants/AntsLeaveMessage'
import axios from 'axios'
import AntsImageUpload from '@/components/ants/AntsImageUpload'
import pick from 'lodash.pick'

const localStorageKey = 'leaving-message-qq-info'
export default {
  name: 'leavingMessage',
  components: {
    AntsImageUpload,
    AntsLeaveMessage,
    AntsBaberrage
  },
  data() {
    return {
      form: this.$form.createForm(this),
      url: {
        list: '/leaveMessage/list',
        add: '/leaveMessage/add',
        addReply: '/leaveMessage/addReply'
      },
      leavingMessage: {},
      data: [],
      /* 分页参数 */
      pagination: {
        current: 1,
        pageSize: 5,
        pageSizeOptions: ['10'],
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      /* 排序参数 */
      sorter: {
        column: 'createTime',
        order: 'desc'
      },
      personInfoVisible: false,
      confirmLoading: false,
      isChidSend: false,
      labelCol: {
        xs: {span: 24},
        sm: {span: 4}
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 18}
      },
      validatorRules: {
        nickname: {
          rules: [
            {required: true, message: '请输入昵称!'}
          ]
        },
        email: {
          rules: [
            {required: true, message: '请输入邮箱!'},
            {validator: this.validateEmail}
          ]
        }
      },
      codeCharacter: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F'],
      leavingMessageSize: 0
    }
  },
  created() {
    this.loadData()
  },
  methods: {
    // 根据QQ号获取QQ信息
    getQqInfo() {
      var that = this
      this.form.validateFields((err, values) => {
        Object.assign(this.leavingMessage, values)
        axios.get('https://api.sumt.cn/api/qq.info.php?token=HTWzReW9hxzMYyx9fhw6kHG9&qq=' + this.leavingMessage.nickname).then(function (response) {
          if (response.data.code === 200) {
            that.$nextTick(() => {
              response.data.url = ''
              if (response.data.name == '') {
                // response.data.nickname = that.chooseFourWords()
                response.data.nickname = response.data.qq
                that.$message.info('暂未获取到昵称！')
              } else {
                response.data.nickname = response.data.name
              }
              response.data.avatar = response.data.qlogo
              that.form.setFieldsValue(pick(response.data, 'nickname', 'email', 'avatar'))
              window.localStorage.setItem(localStorageKey, JSON.stringify(response.data))
            })
          }

        }, function () {
        }).catch(function (error) {
        })
      })
    },
    // 校验邮箱
    validateEmail(rule, value, callback) {
      if (!value) {
        callback()
      } else {
        if (new RegExp(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/).test(value)) {
          callback()
        } else {
          callback('请输入正确格式的邮箱!')
        }
      }
    },
    // 加载数据
    loadData() {
      this.data = []
      var params = this.getQueryParams()// 查询条件
      getAction(this.url.list, params).then(res => {
        if (res.success) {
          this.data = res.result.records
          this.pagination.total = res.result.total
          this.leavingMessageSize = res.result.size
        }
      })
    },
    // 获取查询参数
    getQueryParams() {
      const param = Object.assign(this.sorter)
      // 获取查询条件
      param.pageNo = this.pagination.current
      param.pageSize = this.pagination.pageSize
      param.status = '0,2'
      return filterObj(param)
    },
    // 留言  点击确定按钮
    doSend(content) {
      // if (!new RegExp(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/).test(this.leavingMessage.mail)) {
      if (content === undefined || content === null || content.length === 0 || content.trim().length === 0) {
        this.$message.error('你也得留下一点内容才行撒！')
      } else {
        this.personInfoVisible = true
        this.$nextTick(() => {
          const qqinfo = JSON.parse(window.localStorage.getItem(localStorageKey))

          qqinfo.nickname = qqinfo.name

          qqinfo.avatar = qqinfo.qlogo
          this.form.setFieldsValue(pick(qqinfo, 'nickname', 'email', 'url', 'avatar'))
        })
        this.isChidSend = false
        this.leavingMessage.content = content
      }
    },
    // 留言 提交
    doSendSubmit(values) {
      values.content = this.leavingMessage.content
      postAction(this.url.add, values).then(res => {
        if (res.success) {
          // this.leavingMessage.content = ''
          // this.leavingMessage.avatar = res.message
          // this.leavingMessage = {}
          this.loadData()
          this.$message.success('操作成功！')
          this.personInfoVisible = false
          this.confirmLoading = false
        }
      }).catch(error => {
        this.$message({
          dangerouslyUseHTMLString: true,
          message: error.message,
          type: 'warning'
        })
      })
    },
    // 留言回复  点击确定按钮
    doChidSend(text, targetUserId, parentId) {
      if (text === undefined || text === null || text.length === 0 || text.trim().length === 0) {
        this.$message.error('你也得留下一点内容才行撒！')
      } else {
        this.personInfoVisible = true
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(JSON.parse(window.localStorage.getItem(localStorageKey)), 'nickname', 'email', 'url', 'avatar'))
        })
        this.leavingMessage.content = text
        this.leavingMessage.targetUserId = targetUserId
        this.leavingMessage.pid = parentId
        this.isChidSend = true
      }
    },
    // 留言回复  提交
    doChidSendSubmit(values) {
      values.content = this.leavingMessage.content
      values.targetUserId = this.leavingMessage.targetUserId
      values.pid = this.leavingMessage.pid
      postAction(this.url.addReply, values).then(res => {
        if (res.success) {
          this.loadData()
          this.$message.success('操作成功！')
          this.personInfoVisible = false
          this.confirmLoading = false
        }
      }).catch(error => {
        this.$message({
          dangerouslyUseHTMLString: true,
          message: error.message,
          type: 'warning'
        })
      })
    },
    onShowSizeChange(current, pageSize) {
      this.pagination.current = current
      this.pagination.pageSize = pageSize
      this.loadData()
    },
    onChange(pageNumber) {
      this.pagination.current = pageNumber
      this.loadData()
    },
    doCancel() {
      this.personInfoVisible = false
    },
    doOk() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          window.localStorage.setItem(localStorageKey, JSON.stringify(values))
          if (!that.isChidSend) {
            // 留言提交
            this.doSendSubmit(values)
          } else {
            // 回复留言提交
            this.doChidSendSubmit(values)
          }
        }
      })
    },
    //随机选择四个文字，加入到 words 数组
    chooseFourWords() {
      let arr = '';
      for (let i = 0; i < Math.ceil(Math.random() * 5); i++) {
        let tempStr = '%u';

        // 随机选择第三位字符
        let temp_3 = 4 + Math.ceil(Math.random() * 5);
        tempStr += this.codeCharacter[temp_3];

        //随机选择第四位字符
        let temp_4;
        if (temp_3 === 4) {
          temp_4 = 14 + Math.round(Math.random());
        } else {
          temp_4 = Math.round(Math.random() * 15);
        }
        tempStr += this.codeCharacter[temp_4];

        //随机选择第五位字符
        let temp_5;
        if (temp_4 === 15 && temp_3 === 9) {
          temp_5 = Math.round(Math.random() * 10);
        } else {
          temp_5 = Math.round(Math.random() * 15);
        }
        tempStr += this.codeCharacter[temp_5];

        //随机选择第六个字符
        let temp_6;
        if (temp_3 === 9 && temp_4 === 15 && temp_5 === 10) {
          temp_6 = Math.round(Math.random() * 5);
        } else {
          temp_6 = Math.round(Math.random() * 15);
        }
        tempStr += this.codeCharacter[temp_6];

        arr += unescape(tempStr)
      }

      return arr;
    },
  }

}
</script>

<style>
.commentReview {
  color: #999;
  display: inline;
  font-weight: 400 !important;
}
.spin-content {
  border: 1px solid #91d5ff;
  background-color: #e6f7ff;
  padding: 30px;
  height: 100px;
}
</style>

